import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/Layout/index.vue'
import Home from '@/views/Layout/home.vue'
import Cart from '@/views/Layout/cart.vue'
import Category from '@/views/Layout/category.vue'
import User from '@/views/Layout/user.vue'

import store from '@/store'

// 使用路由懒加载，按需加载，用到时再加载
const Login = () => import('@/views/Login/index.vue')
const Search = () => import('@/views/Search/index.vue')
const SearchList = () => import('@/views/Search/list.vue')
const MyOrder = () => import('@/views/MyOrder/index.vue')
const Pay = () => import('@/views/Pay/index.vue')
const Prodetail = () => import('@/views/Prodetail/index.vue')
const NotFound = () => import('@/views/NotFound/index.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: 'home',
      children: [
        { path: 'home', component: Home },
        { path: 'cart', component: Cart },
        { path: 'category', component: Category },
        { path: 'user', component: User }
      ]
    },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    { path: '/prodetail/:id', component: Prodetail },
    { path: '/pay', component: Pay },
    { path: '/myorder', component: MyOrder },
    { path: '*', component: NotFound }
  ]
})

// 所有的路由在真正被访问之前，都会经过前置路由守卫，放行了才会到达对应页面
// 全局前置导航守卫
// to 到哪去，包含完整的路由对象（路由，参数...）
// from 从哪来
// next 放不放行
// （1）next() ：直接放行，到 to 的对象
// （2）next(路径)：拦截，拦截到 next 中配置的路径

// 定义一个权限访问数据
const authUrls = ['/pay', '/myorder']

router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行
    next()
    return
  }
  // 权限页面，需要判断 token
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
